from django.shortcuts import render, redirect
from booktest.models import BookInfo, HeroInfo
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator

def index(request):
    return render(request, 'booktest/form.html')

def getbooks(request):
    booklist = BookInfo.objects.all()
    context = {'booklist':booklist}
    return render(request, 'booktest/getbooks.html', context)

# Get
def getbook_by_id(request):
    bookid = request.GET.get('id')
    book = BookInfo.objects.get(pk=bookid)
    return HttpResponse(book.btitle)

# Post Session
def getform(request):
    request.session['user_name'] = request.POST.get('username')
    booktitle = request.POST.get('booktitle')
    book = BookInfo.objects.get(btitle=booktitle)
    response_str = str(book.id) + book.btitle + str(book.bcommet) 
    return HttpResponse(response_str)

# 回话session
def getsession(request):
    current_user = request.session['user_name']
    return HttpResponse(current_user)

# 模板继承
def basemodel_exbook(request):
    return render(request, 'booktest/base_model_extend_book.html')

# 正则带组参
def gethero_by_id(request, id):
    hero = HeroInfo.objects.get(pk=id)
    return HttpResponse(hero.hname)

# 重定向
def redirect_test(request):
    return redirect('/getbooks')

# 重定向有参反向解析
def redirect_reverse_arg(requrest):
    return HttpResponseRedirect(reverse('get_hero', args=(3,)) )

# 重定向无参反向解析
def redirect_reverse(requrest):
    return redirect(reverse('get_books'))

# 分页
def getbook_page1(request):
    booklist = BookInfo.objects.all()
    page_mger = Paginator(booklist, 4)  # 每页4条记录
    page1_booklist = page_mger.page(1)
    page_rangelist = page_mger.page_range
    context = {'page1_booklist':page1_booklist, 'page_rangelist':page_rangelist}
    return render(request, 'booktest/showpage1.html', context)

# ajax
def visit_ajax(request):
    return render(request, 'booktest/ajax.html')
def ajax_test(request):
    myvalue = request.GET.get('value')
    return JsonResponse({'data':myvalue})



    
